import React from 'react';
import { Upload } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile } from 'antd/es/upload/interface';
import { HNotification } from "@/config/route/route-func";
import Modal from "antd/es/modal/Modal";
import { util } from "@/common/util";
import LoginUser from '@/config/user';


class AdminUploadFileProps {
  disabled?: boolean = false;
  name?:string;
  maxCount!:number;
  filename?: string;
  transmission?: any;
  actionUrl?: string;
  formIsFileList?: any;
  // children?: React.ReactNode;

}

export default class HUpload extends React.Component<AdminUploadFileProps, any> {

  state = {
    fileList: [],
    previewImageUrl: "",
    previewVisible: false,
    previewTitle: "",
    loading: false,
  }

  constructor(props: AdminUploadFileProps) {
    super(props);
    this.beforeUpload = this.beforeUpload.bind(this)
    this.customRequest = this.customRequest.bind(this)
    this.handlePreview = this.handlePreview.bind(this)
    this.onRemove = this.onRemove.bind(this)

    let values: any = [];
    if (props.formIsFileList) {
      props.formIsFileList.forEach((element: any) => {
        values.push({ url: element, percent: "done", name:"文件"})
      });
    }



    this.state = {
      previewTitle: "",
      previewImageUrl: "",
      previewVisible: false,
      loading: false,
      fileList: values,
    }
  }
  componentDidMount() {
    this.setState({
      loading:false
    })

  }



  beforeUpload = (file: RcFile) => {
    const isLt2M = file.size / 1024 / 1024 < 20
    const lastfileName = util.lastfileName(file.name)
    const isJpgOrPng = util.lastfileNameList(lastfileName)
    if (!isJpgOrPng) {
      HNotification.error({ message: 'You can only upload JPG/PNG file!' })
    }
    if (!isLt2M) {
      HNotification.error({ message: 'You can only upload JPG/PNG file!' })
    }
    return isJpgOrPng && isLt2M;
  };

  onRemove(file: any) {
    let newArr = this.state.fileList.filter((item:any)=>item.uid !== file.uid)

this.setState({
fileList:newArr
});
this.props.transmission(newArr)
  }

  formRef = React.createRef();
  customRequest(options: any) {
    const { transmission } = this.props
    const formData = new FormData();
    const files: any = options.file
    formData.append('files', files)
    fetch('https://gyltest.chongxiaopai.com/gyl/file/fileResource/uploadFiles', {
      method: 'post',
      headers: {
        'Token': LoginUser.token || ''
      },
      body: formData
    }).then(response => {
      return response.json()
    }).then((data) => {
      if (data.code === 200) {
        const accessUrl = data.data[0];
        this.setState((preState: any) => ({
          fileList: [...preState.fileList, { url: accessUrl, percent: "done",name:"文件" }],
          previewImageUrl: accessUrl,
          previewVisible: false,
          loading: false,
          previewTitle: accessUrl?.substring(accessUrl?.lastIndexOf('/') + 1)
        }), () => {
          let list: any = [];
          this.state.fileList.forEach((item) => {
            //@ts-ignore
            list.push(item)
          })
          this.props.transmission(list)
        })

        options.onSuccess();
      } else {
        this.setState({
          loading: false,
        })
        HNotification.error({ message: data.message })
        options.onError();
      }
    })

  };


  handlePreview(file: UploadFile) {
    this.setState({
      previewImageUrl: file.thumbUrl ? file.thumbUrl : file.url,
      previewVisible: true,
      previewTitle: file.name || file.url?.substring(file.url?.lastIndexOf('/') + 1)
    })
  };

  uploadChin() {
    const { loading } = this.state;
    const { disabled } = this.props;
    if (!!disabled) {
      return null;
    } else if (loading) {
      return <>
        <div>
          <LoadingOutlined />
          <div style={{ marginTop: 8 }}>添加文件</div>
        </div>
      </>
    } else {
      return <>
        <div>
          <PlusOutlined />
          <div style={{ marginTop: 8 }}>添加文件</div>
        </div>
      </>
    }


  }

  render() {
    const { previewVisible, previewTitle, previewImageUrl, fileList } = this.state;
    const { disabled, actionUrl,name ,maxCount } = this.props;
    const layout = { disabled }
    return (
      <>
        <Upload
          {...layout}
          maxCount={maxCount}
          name={name}
          fileList={fileList ? fileList : []}
          listType="picture-card"
          showUploadList={{ showPreviewIcon: true, showRemoveIcon: true }}
          action={actionUrl}
          customRequest={this.customRequest}
          onPreview={this.handlePreview}
          onRemove={this.onRemove}
          beforeUpload={this.beforeUpload}
        >
          {fileList.length >= maxCount ? null : this.uploadChin()}
        </Upload>

        <Modal open={previewVisible} title={previewTitle} footer={null} onCancel={() => {
          this.setState({
            previewImageUrl: "",
            previewVisible: false,
            previewTitle: ""
          })
        }}>
          <img alt="example" style={{ width: '100%' }} src={previewImageUrl} />
        </Modal>
      </>
    );
  }
};
